package com.ilink.teacherservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ilink.ilinkapi.client.UserServiceClient;
import com.ilink.ilinkapi.dto.teacher.CrudCourseRequest;
import com.ilink.ilinkapi.dto.teacher.SortOrderUpdateDTO;
import com.ilink.ilinkcommon.domain.PO.studyservice.CourseSource;
import com.ilink.ilinkcommon.domain.PO.studyservice.FileTranscriptionTaskResponse;
import com.ilink.ilinkcommon.domain.PO.studyservice.StudyCourseFile;
import com.ilink.ilinkcommon.domain.PO.studyservice.StudyFileSource;
import com.ilink.ilinkcommon.domain.PO.studyservice.StudyWebSourse;
import com.ilink.ilinkcommon.domain.PO.trainingCamp.TrainingCamp;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.domain.User;
import com.ilink.ilinkcommon.log.courseaccess.CourseAccessLog;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.ilinkcommon.utils.BeanUtils;
import com.ilink.ilinkcommon.utils.UserContext;
import com.ilink.teacherservice.entity.DTO.StudyCourseFileResponse;
import com.ilink.teacherservice.entity.DTO.StudyResourceDto;
import com.ilink.teacherservice.entity.DTO.StudySourceFileResponse;
import com.ilink.teacherservice.entity.VO.CourserReviewResponse;
import com.ilink.teacherservice.entity.VO.TrainingCampListResponse;
import com.ilink.teacherservice.mapper.CourseSourceMapper;
import com.ilink.teacherservice.mapper.FileContentMapper;
import com.ilink.teacherservice.mapper.FileTranscriptionMapper;
import com.ilink.teacherservice.mapper.StudyCourseFileMapper;
import com.ilink.teacherservice.mapper.StudyFileSourceMapper;
import com.ilink.teacherservice.mapper.StudyWebSourseMapper;
import com.ilink.teacherservice.service.OfflineExportService;
import com.ilink.teacherservice.service.StudyCourseFileService;
import com.ilink.teacherservice.service.StudyaboutTeacherService;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/teacher/StudySpaceTeacher")
public class StudyaboutTeacherController {

    @Autowired
    private CourseSourceMapper courseSourceMapper;

    @Autowired
    private StudyFileSourceMapper studyFileSourceMapper;


    @Autowired
    private StudyWebSourseMapper studyWebSourseMapper;

    @Autowired
    private StudyCourseFileMapper studyCourseFileMapper;
    @Autowired
    private StudyaboutTeacherService studyaboutTeacherService;

    @Autowired
    private StudyCourseFileService studyCourseFileService;
    @Autowired
    private FileContentMapper fileContentMapper;
    @Autowired
    private FileTranscriptionMapper fileTranscriptionMapper;

    @Autowired
    private OfflineExportService offlineExportService;
    @Autowired
    private UserServiceClient userServiceClient;

    /**
     * @return
     * @Author haungqing
     * @Description 资源拖拉拽移动排序
     * @Date 上午8:44 2024/9/19
     * @Param
     **/

    //拖拉拽接口
    @MethodLog
    @PostMapping("/updateSortOrder")
    public R updateSortOrder(@RequestBody SortOrderUpdateDTO request) {
        Long parentId = request.getParentId(); // 前端传来的 fileId
        List<Long> sortedIds = request.getSortedIds(); // 前端传来的 resourceId 列表

        // 调用服务层进行排序更新
        boolean success = studyCourseFileService.updateSortOrder(parentId, sortedIds);

        if (success) {
            return R.ok("排序更新成功");
        } else {
            return R.error("排序更新失败");
        }
    }


    /**
     * @return com.ilink.ilinkcommon.domain.R
     * @Author ZhangBo
     * @Description 创建课程
     * @Date 9:27 2024/9/21
     * @Param [courseJson, files]
     **/
    @MethodLog("创建课程")
    @PostMapping("/createCourse")
    public R createCourse(
        @RequestParam("course") String courseJson,
        @RequestParam("files") List<MultipartFile> files) {
        try {
            // 解析 JSON 数据
            ObjectMapper objectMapper = new ObjectMapper();
            CrudCourseRequest course = objectMapper.readValue(courseJson, CrudCourseRequest.class);
            String userId = UserContext.getUserId();
            boolean result = studyaboutTeacherService.createCourseWithFolder(
                userId, course, files);
            if (result) {
                return R.ok("课程创建成功");
            } else {
                return R.error("课程创建失败");
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }



    /**
     * @return com.ilink.ilinkcommon.domain.R
     * @Author ZhangBo
     * @Description 修改课程信息，备注：courseJson是课程信息，files是相关图片
     * @Date 9:27 2024/9/21
     * @Param [courseId, courseJson, files]
     **/
    @MethodLog("修改课程信息")
    @PostMapping("/modify_course")
    public R modifyCourse(
        @RequestParam("courseId") Long courseId,
        @RequestParam("course") String courseJson,
//                          @RequestBody CrudCourseRequest course,
        @RequestParam("files") List<MultipartFile> files) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            CrudCourseRequest course = objectMapper.readValue(courseJson, CrudCourseRequest.class);
            String userId = UserContext.getUserId();
            boolean result = studyaboutTeacherService.updateCourseById(
                userId, courseId, course, files);
            if (result) {
                return R.ok("课程修改成功");
            } else {
                return R.error("课程修改成功");
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    //删除课程文件，删除课程记录和所有的课程资源
    @MethodLog("删除课程文件，删除课程记录和所有的课程资源")
    @GetMapping("/deleteFiles")
    public R deleteFiles(@RequestParam Long courseFileId, @RequestParam Long courseId) {
        try {
            boolean result = studyaboutTeacherService.deleteCoursefileBycourseFile(courseFileId,
                courseId);
            if (result) {
                log.info("课程文件及其资源删除成功" + courseFileId);
                return R.ok("课程文件及其资源删除成功");
            } else {
                log.error("课程文件及其资源删除时发生错误：" + courseFileId);
                return R.error("课程文件及其资源删除失败");
            }
        } catch (Exception e) {
            log.error("课程文件及其资源删除失败" + courseFileId + e.getMessage());
            return R.error(e.getMessage());
        }
    }


    //删除课程资源
    @MethodLog("删除课程资源")
    @GetMapping("/deleteSources")
    public R deleteSources(@RequestParam Long source_id, @RequestParam String type) {
        try {
            boolean result = studyaboutTeacherService.deleteSourcesfile(source_id, type);
            if (result) {
                log.info("课程资源删除成功" + source_id);
                return R.ok("课程资源删除成功");
            } else {
                log.error("课程资源删除时发生错误：" + source_id);
                return R.error("课程资源删除失败");
            }
        } catch (Exception e) {
            // 可以根据异常类型或消息，返回一个合适的错误响应
            log.error("课程资源删除时发生错误：" + source_id, e);
            return R.error("课程资源删除时发生错误：" + source_id, e.getMessage());
        }
    }

    // 查看所有课程，返回 JSON 格式的层级文件树，增加了按照 sortOrder 排序
    @MethodLog("查看所有课程")
    @GetMapping("/getAllCourses")
    public R getAllCourses(@RequestParam Long courseFileId) {
        try {
            StudyCourseFileResponse courseResourceTree = new StudyCourseFileResponse();
            courseResourceTree.setCourseFileId(courseFileId);
            courseResourceTree.setChildFiles(
                studyaboutTeacherService.getCourseFiles(courseFileId, null)); // 传入 null 表示不过滤
            return R.ok(courseResourceTree);
        } catch (Exception e) {
            log.error("获取所有课程失败，courseFileId: {}", courseFileId, e);
            return R.error("获取课程失败：" + e.getMessage());
        }
    }





    /*// 查看所有课程，返回json格式的层级文件树,增加了按照sortOrder排序
    @GetMapping("/getallCourese")
    public R getAllCourses(
        @RequestParam Long courseFileId) {
        try {
            StudyCourseFileResponse courseResourceTree = new StudyCourseFileResponse();
            courseResourceTree.setCourseFileId(courseFileId);
            courseResourceTree.setChildFiles(studyaboutTeacherService.getCourseFiles(courseFileId, null));  // 传入 null 表示不过滤
            return R.ok(courseResourceTree);
        }
        catch (Exception e) {
            log.error(courseFileId+"课程层级树查看失败", e);
            return R.error(e.getMessage());
        }

    }*/

    //获取文件夹下对应资源
    @MethodLog("获取文件夹下对应资源")
    @GetMapping("/getCourseFileSources")
    public R getCourseFileSources(@RequestParam Long courseFileId) {
        try {
            List<StudySourceFileResponse> SourceFiles = studyaboutTeacherService.getSourseFiles(
                courseFileId, "");
            List<StudyWebSourse> webSourse = studyWebSourseMapper.getWebByCourseFileId(
                courseFileId);
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("studySourceFiles", SourceFiles);
            responseMap.put("studyWebSourse", webSourse);
            return R.ok(responseMap);
        } catch (Exception e) {
            log.error(courseFileId + "获取文件夹下对应资源失败", e);
            return R.error(e.getMessage());
        }

    }


    // 获取子文件夹和资源(排序)
    @MethodLog("获取子文件夹和资源(排序)")
    @GetMapping("/sorted-resources")
    public R getSortedResources(@RequestParam Long courseFileId,
        @RequestParam(required = false) String sentence) {
        try {
            List<StudyResourceDto> sortedResources = studyaboutTeacherService.getSortedResources(
                courseFileId, sentence);
            return R.ok(sortedResources);
        } catch (Exception e) {
            // 您可以在这里记录错误日志
            return R.error(e.getMessage());
        }
    }


    //根据文件夹ID给出子文件夹和资源
    @MethodLog("根据文件夹ID给出子文件夹和资源")
    @GetMapping("/getCourseFile")
    public R getCourseFile(@RequestParam Long courseFileId, @RequestParam String type,
        @RequestParam(required = false, defaultValue = "") String sentence) {
        try {
            Map<String, Object> responseMap = new HashMap<>();
            if (type.equals("folder")) {
                List<StudyCourseFileResponse> courseFiles = studyaboutTeacherService.getCourseFiles(
                    courseFileId, sentence);
                responseMap.put("studyCourseFiles", courseFiles);
            }
            if (type.equals("Source")) {
                List<StudySourceFileResponse> SourceFiles = studyaboutTeacherService.getSourseFiles(
                    courseFileId, sentence);
                List<StudyWebSourse> webSourse = studyWebSourseMapper.getWebByCourseFileId(
                    courseFileId);
                //依据sentence对 List<StudyWebSourse>中的Name进行过滤
                if (sentence != null && !sentence.isEmpty()) {
                    webSourse = webSourse.stream()
                        .filter(response -> response.getWebName().contains(sentence))
                        .collect(Collectors.toList());  // 受限于JDK版本使用 collect 替代 toList
                }
                responseMap.put("studyWebSourse", webSourse);
                responseMap.put("studySourceFiles", SourceFiles);
            }
            return R.ok(responseMap);
        } catch (Exception e) {
            log.error(courseFileId + "获取文件夹子文件夹和资源", e);
            return R.error(e.getMessage());
        }

    }

    //获取所有上传文件的状态
    @MethodLog("获取所有上传文件的状态")
    @GetMapping("/getAllSourcesState")
    public R getAllSourcesState(
        @RequestParam(required = false, defaultValue = "") String sentence) {
        String userId = UserContext.getUserId();
        try {
            List<StudySourceFileResponse> SourceFiles = studyaboutTeacherService.getSourseFilesALL(
                userId, sentence);
            return R.ok("获取所有资源成功", SourceFiles);
        } catch (Exception e) {
            log.error("用户" + userId + "获取所有上传文件的状态失败", e);
            return R.error(e.getMessage());
        }


    }

    //根据用户ID给出对应课程列表
    @MethodLog("根据用户ID给出对应课程列表")
    @GetMapping("/getCourse")
    public R getCourse(@RequestParam(required = false, defaultValue = "") String sentence) {
        try {
            String userId = UserContext.getUserId();
            List<StudyCourseFileResponse> courseResourceTree = studyaboutTeacherService.getUserCourseByuserId(
                userId, sentence);
            return R.ok(courseResourceTree);
        } catch (Exception e) {
            log.error("用户" + UserContext.getUserId() + "获取课程列表失败", e);
            return R.error(e.getMessage());
        }

    }

    //修改文件夹命名
    @MethodLog("修改文件夹命名")
    @PostMapping("/updateCourseFileName")
    public R updateCourseFileName(@RequestParam Long courseFileId, @RequestParam String newFileName,
        @RequestParam String type) {
        try {
            // 创建一个 UpdateWrapper 对象
            if (type.equals("文件夹")) {
                UpdateWrapper<StudyCourseFile> updateWrapper = new UpdateWrapper<>();
                // 设置要更新的列和值
                updateWrapper.set("name", newFileName);
                // 通过条件指定要更新的行，例如根据 id 更新
                updateWrapper.eq("courseFile_id", courseFileId);
                // 执行更新操作
                studyCourseFileMapper.update(null, updateWrapper);

            } else if (type.equals("音视频资源")) {
                UpdateWrapper<CourseSource> updateWrapper = new UpdateWrapper<>();
                // 设置要更新的列和值
                updateWrapper.set("file_name", newFileName);
                // 通过条件指定要更新的行，例如根据 id 更新
                updateWrapper.eq("coursesource_id", courseFileId);
                // 执行更新操作
                courseSourceMapper.update(null, updateWrapper);
            } else if (type.equals("资源")) {
                UpdateWrapper<StudyFileSource> updateWrapper = new UpdateWrapper<>();
                // 设置要更新的列和值
                updateWrapper.set("file_name", newFileName);
//            updateWrapper.set("")
                // 通过条件指定要更新的行，例如根据 id 更新
                updateWrapper.eq("filesource_id", courseFileId);
                // 执行更新操作
                studyFileSourceMapper.update(null, updateWrapper);
            } else if (type.equals("网页资源")) {
                StudyWebSourse webSourse = studyWebSourseMapper.selectById(courseFileId);
                if (webSourse != null) {
                    webSourse.setWebName(newFileName);
                    webSourse.setUploadedAt(new Date());
                    studyWebSourseMapper.updateById(webSourse);
                    return R.ok("修改网页名称成功");
                }
                return R.error("未找到该网页资源");
            } else {
                return R.error("类型错误");
            }
            return R.ok("修改成功");
        } catch (Exception e) {
            log.error("修改文件夹名称失败" + courseFileId, e);
            return R.error(e.getMessage());
        }


    }


    //新建章节
    @MethodLog("新建章节")
    @PostMapping("/createChapter")//上层文件夹的ID
    public R createChapter(@RequestParam String file_name, @RequestParam Long courseFile_id) {
//        User user = (User) userDetails;
        try {
            boolean result = studyaboutTeacherService.createChapter(file_name, courseFile_id);
            if (result) {
                return R.ok("章节创建成功");
            } else {
                return R.error("章节创建失败");
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }


    }

    @MethodLog
    @PostMapping("/newcreateChapter")
    public R createChapter(@RequestParam String file_name,
        @RequestParam Long courseFile_id,
        @RequestParam Integer sort_order) {
        try {
            boolean result = studyaboutTeacherService.newcreateChapter(file_name, courseFile_id,
                sort_order);
            if (result) {
                return R.ok("章节创建成功");
            } else {
                return R.error("章节创建失败");
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }


    //课程-章节-小节
    //资源移动（到当前课程的其他小节）
    @MethodLog("资源移动（到当前课程的其他小节）")
    @PostMapping("/moveResourse")
    public R moveResourse(
        @RequestParam Long resourceId,
        @RequestParam String resourceType,
        @RequestParam String newPath,
        @RequestParam Long courseId,
        @RequestParam(defaultValue = "-1") int sortOrder) {
        try {
            // 使用 newPath 查找新的文件夹 ID
            StudyCourseFile newFolder = studyCourseFileMapper.selectOne(
                new QueryWrapper<StudyCourseFile>().eq("file_path", newPath)
                    .eq("course_id", courseId)
            );
            if (newFolder == null) {
                return R.error("无效目标路径");
            }

            switch (resourceType.toLowerCase()) {
                case "资源":
                    return studyCourseFileService.moveDocumentResource(resourceId, newFolder,
                        courseId, sortOrder);
                case "音视频资源":
                    return studyCourseFileService.moveAudioVideoResource(resourceId, newFolder,
                        courseId, sortOrder);
                case "网页资源":
                    return studyCourseFileService.moveWebResource(resourceId, newFolder, courseId,
                        sortOrder);
                default:
                    return R.error("无效资源");
            }
        } catch (Exception e) {
            log.error("资源移动失败" + resourceId, e);
            return R.error(e.getMessage());
        }


    }

    //小节移动（到当前课程的其他章节）
    @MethodLog("小节移动（到当前课程的其他章节）")
    @PostMapping("/moveSection")
    public R moveSection(
        @RequestParam Long sectionId,
        @RequestParam Long targetChapterId,
        @RequestParam Long courseId,
        @RequestParam(defaultValue = "-1") int sortOrder) {

        try {
            return studyCourseFileService.moveSection(sectionId, targetChapterId, courseId,
                sortOrder);
        } catch (Exception e) {
            log.error("课程" + courseId + "的" + sectionId + "小节移动失败", e);
            return R.error(e.getMessage());
        }


    }


    //给出coursesource_id查询音视频转写结果
    @CourseAccessLog
    @MethodLog("查询音视频转写结果")
    @GetMapping("/getSourceTransResult")
    public R getSourceFile(@RequestParam Long courseSourceId) {
//        FileTranscriptionTaskResponse fileTranscriptionTaskResponse =  courseSourceMapper.selectTransResultById(courseSourceId);
        CourseSource courseSource = courseSourceMapper.selectById(courseSourceId);
        FileTranscriptionTaskResponse fileTranscriptionTaskResponse = fileTranscriptionMapper.selectOne(
            new LambdaQueryWrapper<FileTranscriptionTaskResponse>().eq(
                FileTranscriptionTaskResponse::getTaskId, courseSource.getTaskId()));
        if (fileTranscriptionTaskResponse == null) {
            return R.error("课程转写资源不存在");
        }
        return R.ok(fileTranscriptionTaskResponse);
    }

    @MethodLog
    @GetMapping("/filecontent")
    public R getFileContentByPage(@RequestParam Long filesource_id) {
        try {
            // 获取文件的内容
            //Map<String, JsonNode> fileContent = fileResponseService.getContent(tongyiId);
            StudyFileSource.FileContentDTO fileContent1 = fileContentMapper.selectIntroductionTranslationMindmapByFileSourceId(
                filesource_id);
            System.out.println("文件内容" + fileContent1);

            return R.ok("文件内容", fileContent1);
        } catch (Exception e) {
            return R.error("读取文件内容失败: " + e.getMessage());
        }
    }


    @MethodLog
    //记录更新用于对于某课程的学习情况
    @PutMapping("/updateCourseFileStudyRecord")
    public R updateCourseFileStudyRecord(@RequestParam Long courseSourceId,
        @RequestParam(required = false, defaultValue = "1") Integer time,//单位分钟
        @RequestParam(required = false, defaultValue = "true") boolean isStudyStart
    ) {
        try {
            String userId = UserContext.getUserId();
            // 更新文件名
            int result = studyaboutTeacherService.updateUserCourseStudyRecord(courseSourceId,
                userId, time, isStudyStart);
            if (result>0) {
                return R.ok("用户访问课程记录成功",result);//返回更新的记录数，但不一定更新成功
            } else {
                log.error("用户访问课程记录");
                return R.error("用户访问课程记录失败",result);
            }
        } catch (Exception e) {
            log.error("用户访问课程记录", e);
            return R.error(e.getMessage());
        }
    }

    //获取专题的课程回顾，例如训练营
    @MethodLog("获取某一标签课程的专题回顾")
    @GetMapping("/getCourseReview")
    public R getCourseReview(@RequestParam String coursesTag) {
        try {
            String userId = UserContext.getUserId();
            CourserReviewResponse courseReviewList = studyaboutTeacherService.getCourseReview(
                coursesTag, userId);
            return R.ok("课程回顾", courseReviewList);
        } catch (Exception e) {
            log.error("获取课程回顾失败", e);
            return R.error(e.getMessage());
        }
    }
    //训练营创建接口：
    @MethodLog("创建训练营")
    @PostMapping("/createTrainingCamp")
    public R createTrainingCamp(
        @RequestParam MultipartFile TrainingCampImage,
        @RequestParam("startTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
        @RequestParam("endTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
        @RequestParam("organizerInfo") String organizerInfo,
        @RequestParam("tags") String tags,
        @RequestParam("campName") String campName
    ) {
        try {
            TrainingCamp trainingCamp = new TrainingCamp();
            trainingCamp.setCampName(campName);
            trainingCamp.setStartTime(startTime);
            trainingCamp.setEndTime(endTime);
            trainingCamp.setOrganizerInfo(organizerInfo);
            trainingCamp.setTags(tags);

            boolean result= studyaboutTeacherService.createTrainingCamp(
                trainingCamp, TrainingCampImage);
            if (!result) {
                return R.error("创建训练营失败");
            }
            return R.ok("创建训练营成功");
        } catch (Exception e) {
            log.error("创建训练营失败", e);
            return R.error(e.getMessage());
        }
    }

    //训练营接口：获取训练营列表
    @MethodLog("获取训练营列表")
    @GetMapping("/getTrainingCampList")
    public R getTrainingCampList(
        @RequestParam(required = false, defaultValue = "") String sentence) {
        try {
            List<TrainingCampListResponse> courseReviewList = studyaboutTeacherService.getTrainingCampList(
                sentence);
            return R.ok("训练营列表", courseReviewList);
        } catch (Exception e) {
            log.error("获取训练营列表失败", e);
            return R.error(e.getMessage());

        }

    }
    //专门获取某一期的训练营课程列表详细信息
    @MethodLog("获取某一期训练营课程列表")
    @GetMapping("/getTrainingCampListBytag")
    public R getTrainingCampCourseList(@RequestParam String coursesTag) {
        try {
            List<TrainingCampListResponse> courseReviewList = studyaboutTeacherService.getTrainingCampListBytag(
                    coursesTag);
            return R.ok("训练营课程列表", courseReviewList);
        } catch (Exception e) {
            log.error("获取训练营课程列表失败", e);
            return R.error(e.getMessage());

        }
    }

    //  训练营线下名单导入接口  
    @MethodLog("导入训练营线下参与名单")
    @PostMapping("/import_offline_participants")
    public R importOfflineParticipants(@RequestParam("file") MultipartFile csvFile) {
        try {
            boolean b = offlineExportService.importOfflineTable(csvFile);
            if (!b) {
                return R.error("导入训练营线下名单出现未知错误");
            }
            return R.ok();
        } catch (Exception e) {
            return R.error("导入训练营线下名单出现错误: " + e.getMessage());
        }
    }

    @MethodLog("判断教师是否创建过知识空间")
    @GetMapping("/has_knowledge_space")
    public R hasKnowledgeSpace() {
        try {
            int ans = studyaboutTeacherService.hasKnowledgeSpace();
            if (ans == 1) {
                String courseId=studyaboutTeacherService.getKnowledgeSpaceId();
                String courseFileId = studyaboutTeacherService.getRootFolderId(courseId);
                Map<String, String> result0 = new HashMap<>();
                result0.put("courseId", courseId);
                result0.put("courseFileId", courseFileId);
                return R.ok("该教师已创建过唯一知识空间", result0);
            } else if (ans == 0) {
                String userId=UserContext.getUserId();
                R whoami = userServiceClient.whoami(userId);
                HttpStatus status = HttpStatus.valueOf(whoami.getCode());
                if (!status.is2xxSuccessful()) {
                    log.error(String.format("获取用户信息失败，用户ID: %s", userId));
                }
                User userDetail = BeanUtils.copyBean(whoami.getData(), User.class);
                CrudCourseRequest course=new CrudCourseRequest();
                course.setCourseTag("知识空间");
                course.setCourseName(userDetail.getRealname()+"的知识空间");
                // 判断 courseTag 是否为 "知识空间"
                List<MultipartFile>  files = new ArrayList<>();
                MultipartFile dummyFile = new MockMultipartFile("知识空间", "知识空间封面.txt", "text/plain", "content".getBytes());
                files.add(dummyFile);

                boolean result = studyaboutTeacherService.createCourseWithFolder(
                    userId, course, files);
                if (result) {
                    log.info("课程创建成功");
                } else {
                    log.error("课程创建失败");
                }
                String courseId=studyaboutTeacherService.getKnowledgeSpaceId();
                String courseFileId = studyaboutTeacherService.getRootFolderId(courseId);
                Map<String, String> result1 = new HashMap<>();
                result1.put("courseId", courseId);
                result1.put("courseFileId", courseFileId);
                return R.ok("之前未创建知识空间，已成功创建", result1);
            } else {
                return R.error("发现多个知识空间", ans);
            }
        } catch (Exception e) {
            log.error("判断教师是否创建过知识空间失败", e);
            return R.error(e.getMessage());
        }
    }
}
